<template>
  <div class="page">
    <div class="flex column h-center">
      <div class="relative mt-70">
        <img v-if="!robot.robotWxId"
             src="../../assets/avatar.png"
             class="avatar">
        <img v-if="robot.robotWxId"
             :src="robot.headImgUrl"
             class="avatar">
        <div v-if="robot.robotWxId && robot.state === 0"
             class="live_out flex h-center">
          已离线
        </div>
      </div>

      <div class="fs-18 mt-2 nickname">{{ robot.nickName ? robot.nickName : '播客机器人' }}</div>
      <div class="color-gray fs-14 text-center">{{userCode}}</div>
    </div>

    <div v-if="!robot.robotWxId">
      <button class="btn mt-8"
              @click="toLogin(1)">托管微信号</button>

      <div class="mt-30 fs-12">说明：</div>
      <div class="flex v-top color-gray fs-12 mt-1">
        <div>1.</div>
        <div>
          请用另一台设备（或让好友帮忙）拍摄二维码，或者手机截屏保存二维码后将图片发送给其他手机或者电脑；
        </div>
      </div>
      <div class="flex v-top color-gray fs-12 mt-1">
        <div>2.</div>
        <div>打开需要登录播货助手的微信，打开「扫一扫」扫描二维码登录；</div>
      </div>
      <div class="flex v-top color-gray fs-12 mt-1">
        <div>3.</div>
        <div>
          扫码成功后，系统等待几秒获取账号信息后会自动刷新，请耐心等待；
        </div>
      </div>
      <div class="flex v-top color-gray fs-12 mt-1">
        <div>4.</div>
        <div>为了避免账号异常，请勿重复扫码。</div>
      </div>

      <div class="color-blue flex fs-12 mt-115 h-center"
           @click="show=true">
        如何让您的登录的机器人更加稳定，不容易掉线？
      </div>
    </div>

    <van-popup v-model:show="show"
               style="width: 75%"
               class="flex column pl-3 pr-3">
      <div class="fs-14 b mt-4">如何让机器人更加稳定，不容易掉线？</div>
      <div class="fs-12 mt-3 color-gray">1.用户不要主动关闭微信登陆（比如关闭网页或者windows登陆）；</div>
      <div class="fs-12 mt-1 color-gray">2.用户不要随意更换登陆设备（比如从原先使用的手机换到另外一个手机上登陆）；</div>
      <div class="fs-12 mt-1 color-gray">3.用户应避免在使用中的同时扫码登陆到其他PC端（比如扫码登陆到其他平板类设备）；</div>
      <div class="fs-12 mt-1 color-gray">4.用户应避免随意频繁的更改微信密码（比如手机端收到官方提醒 您微信存在环境异常，请确认是否本人登陆，为了安全，请修改登陆密码之类的）；</div>
      <div class="fs-12 mt-1 color-gray">5.在初始登陆的24小时内，避免频繁操作，如需发送群消息或者个友信息，间隔时间最好为5-8分钟</div>
      <div class="fs-12 mt-1 color-primary b">重点：商家在进行了以上第2点、第3点后，之后的一个周期（8天）内都有一定几率会被官方踢下线！！！</div>
      <button class="mt-4 mb-4 reflesh b"
              @click="show=false">我知道了</button>
    </van-popup>

    <div v-if="robot.robotWxId && robot.state === 0">
      <button class="btn mt-8"
              @click="toLogin(2)">重新登录</button>

      <u class="fs-14 mt-280 color-danger flex h-center"
         @click="logoutWx()">解绑此微信号</u>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'

export default {
  name: 'Index',
  components: {},
  data () {
    return {
      loading: false,
      robot: {
        state: 0,
        headImgUrl: '../../assets/avatar.png',
        nickName: '播课机器人'
      },
      wxType: 1,
      userCode: '',
      userInfo: {},
      show: false
    }
  },
  computed: {},
  async created () {
    const _this = this
    _this.initData()
  },
  methods: {
    async initData () {
      const _this = this
      _this.clearToken()
      await _this.getUserInf()
      await _this.getData()
      if (_this.userCode) {
        _this.getPort()
      }
    },
    clearToken () {
      localStorage.removeItem('Token')
    },
    getUserInf () {
      const _this = this
      return new Promise((resolve, reject) => {
        const userInfo = { nickName: '', avatarUrl: '', userSerialNo: '' }
        if (location.href.indexOf('userCode=') > -1) {
          _this.userCode = location.href.split('userCode=')[1].split('&')[0]
          userInfo.userSerialNo = _this.userCode
        }
        if (location.href.indexOf('nickName=') > -1) {
          userInfo.nickName = decodeURI(location.href.split('nickName=')[1].split('&')[0])
          userInfo.avatarUrl = location.href.split('avatarUrl=')[1].split('&')[0]
          _this.$store.dispatch('setUserInfo', userInfo)
        }
        _this.userInfo = userInfo
        _this.userCode = _this.userInfo.userSerialNo || (localStorage.getItem('UserInfo') && JSON.parse(localStorage.getItem('UserInfo')).userSerialNo)
        resolve()
      })
    },
    getData () {
      const _this = this
      if (!_this.userCode || _this.userCode == 'xxx') {
        _this.$router.replace('/login/404')
      } else {
        return new Promise((resolve, reject) => {
          _this.$post('/User/Login', { userCode: _this.userCode, headImgUrl: _this.userInfo.avatarUrl, nickName: _this.userInfo.nickName }).then((res) => {
            if (res) {
              localStorage.setItem('Token', res)
            }
            resolve()
          }).catch(() => {
            reject()
          })
        })
      }
    },
    getPort () {
      const _this = this
      _this.$post('/WxRobot/GetPorts', { wxType: _this.wxType })
        .then((res) => {
          _this.robot = res[0]
          if (_this.robot.robotWxId && _this.robot.state !== 0) {
            _this.$router.replace('/index')
          }
        })
        .catch((e) => {
          if (e === -10001) {
            _this.$router.replace('/login/noRobot')
          }
        })
    },

    toLogin (value) {
      const _this = this
      _this.$router.push('/login/login')
    },
    async logoutWx () {
      const _this = this
      await _this.$post('/WxRobot/WxRobotLogout', {
        robotWxId: _this.robot.robotWxId,
        deviceId: _this.robot.deviceId,
        wxType: 0,
        reason: [
          {
            reasonType: 1,
            reasonData: '默认'
          }
        ]
      }).then((res) => { })
      _this.getPort()
    },

    reconvert (str) {
      str = str.replace(/(\\u)(\w{1,4})/gi, function ($0) {
        return (String.fromCharCode(parseInt((escape($0).replace(/(%5Cu)(\w{1,4})/g, "$2")), 16)));
      });
      str = str.replace(/(&#x)(\w{1,4});/gi, function ($0) {
        return String.fromCharCode(parseInt(escape($0).replace(/(%26%23x)(\w{1,4})(%3B)/g, "$2"), 16));
      });
      str = str.replace(/(&#)(\d{1,6});/gi, function ($0) {
        return String.fromCharCode(parseInt(escape($0).replace(/(%26%23)(\d{1,6})(%3B)/g, "$2")));
      });

      return str;
    },

    showModal () {
      const _this = this

    }
  }
}
</script>

<style scoped lang="scss">
@import "index";
</style>
